package com.ruoyi.common.utils;

import com.aspose.cells.*;
import com.aspose.pdf.EpubLoadOptions;
import com.aspose.pdf.MarginInfo;
import com.aspose.slides.Presentation;
import com.aspose.words.Document;
import com.aspose.words.ImageSaveOptions;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import org.apache.commons.io.FilenameUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.*;

public class CovertUtil {
    /**
     * 设置签名，若不设置签名，转换后的pdf将会有水印
     *
     * @return
     */
    private static String path;//新增原始路径2024-5-15
    //数据库配置信息 //2024-5-16
    private static String username;
    private  static String password;
    private  static String database;


    public static boolean getLicense(String type) {
        boolean res = false;
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        try {
            InputStream in = loader.getResourceAsStream("license.xml");
            if(type.equals("0")){
                License aposeLic = new License();
                aposeLic.setLicense(in);
                res = true;
            }else if(type.equals("1")) {
                new com.aspose.slides.License().setLicense(in);
                res = true;
                }
            else{
                com.aspose.cells.License license = new com.aspose.cells.License();
                license.setLicense(in);
                res = true;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

    public  static  void  setpath(String srcpath,String tusername,String tpassword,String tdatabase)
    {
        path = srcpath;
        username = tusername;
        password = tpassword;
        database = tdatabase;
    }
    public  static  String csvtopdf (String original_file_path, String transform_file_path,String fileType,String srcPath) throws Exception {
        String desDir = createDir("",srcPath);
        File file = new File(transform_file_path);
        if (!file.getParentFile().exists()) {
            // 不存在则创建父目录及子文件
            file.getParentFile().mkdirs();
            file.createNewFile();
        }
        if(!getLicense(fileType)){
            System.out.println("设置签名失败");
            //return false;
            return  "";
        }

        PdfSaveOptions saveOptions = new PdfSaveOptions();
        //重点，设置所有列放在一页里，会自动适应宽度
        saveOptions.setAllColumnsInOnePagePerSheet(true);

        //saveOptions.setDefaultFont(saveOptions.getDefaultFont());
        Workbook workbook = new Workbook(original_file_path);

        // 转换为PDF
        workbook.save(transform_file_path, saveOptions);
        pdfToImg(transform_file_path,desDir);
        svg(transform_file_path,desDir + "\\out.svg");
        return "";
    }
    /**
     * 文件转换PDF
     * @param original_file_path 源文件路径
     * @param transform_file_path 输出路径
     * @param fileType 转换类型 0：doc转pdf，1：xls转pdf
     * @return
     */
    public static String fileToPdf(String original_file_path, String transform_file_path,String fileType,String srcPath,int ypage) throws Exception {

        String desDir = createDir("",srcPath);
        File file = new File(transform_file_path);
        if (!file.getParentFile().exists()) {
            // 不存在则创建父目录及子文件
            file.getParentFile().mkdirs();
            file.createNewFile();
        }


       try (


                FileInputStream in = new FileInputStream(original_file_path);
                FileOutputStream out = new FileOutputStream(transform_file_path);

        ) {
            //设置签名，若不设置签名转换后的pdf会有水印
            if(!getLicense(fileType)){
                System.out.println("设置签名失败");
                //return false;
                return  "";
            }
            if(fileType.equals("0")){
                //为doc
                //获取doc对象
                Document doc = new Document(in);
                //设置转换页数start2024-05-29
                //com.aspose.pdf.Document document = new com.aspose.pdf.Document(in);
                com.aspose.words.PdfSaveOptions options = new com.aspose.words.PdfSaveOptions();
                /*if(ypage!=0) {
                    options.setPageIndex(0);
                    options.setPageCount(ypage);
                }*/
                doc.save(out, options);
                //end
                //输出
                //doc.save(out, SaveFormat.PDF);
                pdfToImg(transform_file_path,desDir);
                svg(transform_file_path,desDir + "/out.svg");
                //uploadImg(desDir);

            }else if (fileType.equals("1")){

                Presentation pres = new Presentation(in);
                /*************转换页数*************/


                /**********************************/
                pres.save(out, com.aspose.slides.SaveFormat.Pdf);
                //pdfToImg(transform_file_path,"c:\\imges");
                pdfToImg(transform_file_path,desDir);
                svg(transform_file_path,desDir + "/out.svg");
        }
            else if (fileType.equals("2")) {
                //为xls
                //生成工作表
                Workbook workbook = new Workbook(in);
                PdfSaveOptions saveOptions = new PdfSaveOptions();
                //设置页数****************/
               /* if(ypage!=0)
                    saveOptions.setPageCount(ypage);*/
                //重点，设置所有列放在一页里，会自动适应宽度
                saveOptions.setAllColumnsInOnePagePerSheet(true);
                //输出
                workbook.save(out,saveOptions);
                //pdfToImg(transform_file_path,"c:\\imges");
                pdfToImg(transform_file_path,desDir);
                svg(transform_file_path,desDir + "/out.svg");
            }
            else //csv
            {
                // 加载CSV文件
                TxtLoadOptions options = new TxtLoadOptions(LoadFormat.CSV);
                options.setEncoding(Encoding.getEncoding("GB2312"));
                Workbook workbook = new Workbook(in,options);
                PdfSaveOptions saveOptions = new PdfSaveOptions();

                saveOptions.setAllColumnsInOnePagePerSheet(true);

                // 保存为Excel文件
                workbook.save(out,saveOptions );
                pdfToImg(transform_file_path,desDir);
                svg(transform_file_path,desDir + "/out.svg");

            }
            System.out.println("转换成功");
            return  "http://106.3.97.118:8085/crmebimage/public/pdf/";
            //return true;

        } catch (Exception e) {
            e.printStackTrace();
           // return false;
        }
       return "";
    }
    //
    public static String createDir(String despath,String srcpath)
    {
        String destDir = FilenameUtils.separatorsToSystem(despath + srcpath);

        return destDir;
    }
    /**
     * 文件转换PDF
     * @param original_file_path 源文件路径
     * @param transform_file_path 输出路径
     * @param fileType 转换类型 0：doc转pdf，1：xls转pdf
     * @return
     */
    public static String txtToPdf(String original_file_path, String transform_file_path,String fileType,String srcPath) throws Exception {
        String desDir = createDir("",srcPath);
        File file = new File(transform_file_path);
        if (!file.getParentFile().exists()) {
            // 不存在则创建父目录及子文件
            file.getParentFile().mkdirs();
            file.createNewFile();
        }


         try (


        FileInputStream in = new FileInputStream(original_file_path);
        FileOutputStream out = new FileOutputStream(transform_file_path);

        ) {
        //设置签名，若不设置签名转换后的pdf会有水印
        if(!getLicense(fileType)){
            System.out.println("设置签名失败");
            //return false;
            return  "";
        }
        //获取doc对象
        Document doc = new Document(in);
        //输出
        doc.save(out, SaveFormat.PDF);
        pdfToImg(transform_file_path,desDir);
        svg(transform_file_path,desDir + "/out.svg");
        System.out.println("转换成功");
        return  "http://106.3.97.118:8085/crmebimage/public/pdf/";
        //return true;

        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
    public static String downPdf(String original_file_path, String transform_file_path,String fileType,String srcPath) throws Exception {
        String desDir = createDir("",srcPath);
        pdfToImg(original_file_path,desDir);
        svg(original_file_path,desDir + "/out.svg");
        System.out.println("转换成功");
        return  "http://106.3.97.118:8085/crmebimage/public/pdf/";
    }
    public static String EpubToPdf(String original_file_path, String transform_file_path,String fileType,String srcPath) throws Exception {
        String desDir = createDir("",srcPath);
        File file = new File(transform_file_path);
        if (!file.getParentFile().exists()) {
            // 不存在则创建父目录及子文件
            file.getParentFile().mkdirs();
            file.createNewFile();
        }


        try (


                FileInputStream in = new FileInputStream(original_file_path);
                FileOutputStream out = new FileOutputStream(transform_file_path);

        ) {

            EpubLoadOptions epubLoadOptions = new EpubLoadOptions();
            MarginInfo marginInfo  = new MarginInfo(0,0,0,0);
            epubLoadOptions.setMargin(marginInfo);
            com.aspose.pdf.Document document = new com.aspose.pdf.Document(in,epubLoadOptions);
            document.save(out, com.aspose.pdf.SaveFormat.Pdf);
            pdfToImg(transform_file_path,desDir);
            svg(transform_file_path,desDir + "/out.svg");
            System.out.println("转换成功");
            return  "http://106.3.97.118:8085/crmebimage/public/pdf/";
            //return true;

        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * word生成图片(第一页下标从0开始)
     *
     * @param docPath
     * @param imgFullPathName
     */
    public static void wordToImg(String docPath, String imgFullPathName,String fileType) {
//		String filename = Path.GetFileNameWithoutExtension(filePath).ToLower();
        Document words = null;
        try {
            words = new Document(docPath);
        } catch (Exception e) {

            e.printStackTrace();
        }
        if(!getLicense(fileType)){
            System.out.println("设置签名失败");


        }
        // 创建image对象，设置图片格式，分辨率
        ImageSaveOptions imageSaveOptions = new ImageSaveOptions(SaveFormat.PNG);
        imageSaveOptions.setResolution(128);

        int pagecount = 0;
        try {
            pagecount = words.getPageCount();
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        for (int pageindex = 0; pageindex < pagecount; pageindex++) {

            try {
                File file = new File(imgFullPathName + "//img" + pageindex + ".png");
                // 如果不存在，先创建一个文件占位，但没有图片内容
                if (!file.exists()) {
                    file.createNewFile();
                }

                imageSaveOptions.setPageIndex(pageindex);
                words.save(file.getPath(), imageSaveOptions);
            } catch (Exception e) {

                e.printStackTrace();
            }
        }
    }
    private static BufferedImage resize(BufferedImage source, int targetW, int targetH) {
        int type = source.getType();
        BufferedImage target = null;
        double sx = (double) targetW / source.getWidth();
        double sy = (double) targetH / source.getHeight();
        if (sx > sy) {
            sx = sy;
            targetW = (int) (sx * source.getWidth());
        } else {
            sy = sx;
            targetH = (int) (sy * source.getHeight());
        }
        if (type == BufferedImage.TYPE_CUSTOM) {
            ColorModel cm = source.getColorModel();
            WritableRaster raster = cm.createCompatibleWritableRaster(targetW, targetH);
            boolean alphaPremultiplied = cm.isAlphaPremultiplied();
            target = new BufferedImage(cm, raster, alphaPremultiplied, null);
        } else {
            target = new BufferedImage(targetW, targetH, type);
        }
        Graphics2D g = target.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
        g.dispose();
        return target;
    }
    /**
     * pdf文件生成缩略图
     * */
    private static void generatePdfThumbnail(File inputFile, File outputFile, int thumbWidth, int thumbHeight) {
        try {
            PDDocument document = PDDocument.load(inputFile);
            PDFRenderer pdfRenderer = new PDFRenderer(document);
            BufferedImage image = pdfRenderer.renderImageWithDPI(0, 100);
            BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics2D = thumbImage.createGraphics();
            graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
            ImageIO.write(thumbImage, "png", outputFile);
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void pdfToImg(String pdfPath, String imgFullPathName) throws IOException {
        File file = new File(imgFullPathName + "//1.png");
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
            file.createNewFile();
        }
         generatePdfThumbnail(new File(pdfPath), new File(imgFullPathName + "//1.png"),1000,1000);

    }
    public static int countFilesWithExtension(File directory, String extension) {
        if (directory == null || !directory.isDirectory()) {
            return 0;
        }

        int count = 0;
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isFile() && file.getName().toLowerCase().endsWith(extension.toLowerCase())) {
                    count++;
                }
            }
        }
        return count;
    }

  public static void svg_1(String  pdfPath,String outputFilePath)  {

     com.aspose.pdf.Document document = new com.aspose.pdf.Document(pdfPath);

     document.save(outputFilePath, com.aspose.pdf.SaveFormat.Svg);


    }
//pdf转svg
public static void svg(String  pdfPath,String outputFilePath)  {

    com.aspose.pdf.Document document = new com.aspose.pdf.Document(pdfPath);
    document.save(outputFilePath, com.aspose.pdf.SaveFormat.Svg);
    String svgdir = FilenameUtils.getFullPath(outputFilePath);
    int svgcount = countFilesWithExtension(new File(svgdir),".svg");
    System.out.println("文件数量:"+svgcount);
    File oldFile,newFile;
    for(int i=0;i<svgcount;i++)
    {


        if (i==0) {
             oldFile = new File(svgdir+"/out.svg");
             newFile = new File(svgdir+"/"+(i+1)+".view");
        }
        else
        {
             oldFile = new File(svgdir+"/out_"+(i+1)+".svg");
             newFile = new File(svgdir+"/"+(i+1)+".view");

        }
        if(newFile.exists())
        {
          newFile.delete();
        }
       if (oldFile.renameTo(newFile)) {

            System.out.println("文件重命名成功！");
        } else {
            System.out.println("文件重命名失败！");
        }
      /*  try {
            Files.move(oldFile.toPath(), newFile.toPath());
            System.out.println("文件重命名成功！");
        } catch (IOException e){
        System.out.println("文件重命名失败！");
        }*/

    }



}


}
